<template>
  <div class="container">
    <div>
      <div>
        <el-form ref="dataForm" :model="record" :rules="recordRules" label-position="top" size="small"  label-width="110px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="模板编码" prop="code">
                <el-input v-model="record.code" placeholder=""></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模板ID" prop="id">
                <el-input v-model="record.id" placeholder="" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="模板标题" prop="title">
                <el-input v-model="record.title" placeholder=""></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序号" prop="sort">
                <el-input v-model="record.sort" placeholder="排序号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col>
              <el-form-item label="关键字" prop="keyword">
                <el-input v-model="record.keyword" placeholder=""></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col>
              <el-form-item label="模板描述" prop="description">
                <el-input type="textarea"  v-model="record.description"  placeholder="" :autosize="{ minRows: 1}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="存储方式" prop="status">
                <el-select v-model="record.storageMode" size="small" placeholder="" clearable>
                  <el-option v-for="item in storageModeOptions"  :key="item.key" :label="item.display_name" :value="item.key"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模板状态" prop="status">
                <el-select v-model="record.status" size="small" placeholder="" clearable>
                  <el-option v-for="item in statusOptions"  v-if="item.key != '2'" :key="item.key" :label="item.display_name" :value="item.key"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="record.storageMode == '2'">
            <el-col>
              <el-form-item label="模板相对路径" prop="fileRelativePath">
                <el-input v-model="record.fileRelativePath" placeholder=""></el-input>
              </el-form-item>
            </el-col>
          </el-row>
            <!--<el-row :gutter="20">-->
              <!--<el-col>-->
                <!--<el-form-item label="备注" prop="remark">-->
                  <!--<el-input type="textarea"  v-model="record.remark" placeholder="" :autosize="{ minRows: 1}"></el-input>-->
                <!--</el-form-item>-->
              <!--</el-col>-->
            <!--</el-row>-->
          <el-row :gutter="20" v-if="record.storageMode == '1'">
            <el-col :span="12">
              <el-form-item label="模板文件名" prop="fileName">
                <el-input v-model="record.fileName" placeholder="" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模板文件大小" prop="fileSizeName">
                <el-input v-model="recordfileSizeName" placeholder="" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="record.storageMode == '1'">
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                ref="upload"
                name="uploadFile"
                list-type="picture"
                :action="fileUploadUrl"
                :auto-upload="false"
                :file-list="fileList"
                :limit="fileLimit"
                :headers="fileHeaders"
                :on-exceed="handleExceed"
                :before-upload="handleBeforeUpload"
                :on-change="handleChange"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :on-error="handleError"
                :data="fileRecord"
              >
                <el-button slot="trigger" size="mini" type="primary">选取模板文件</el-button>
                <el-button size="mini" type="success" @click="submitUpload">上传模板文件</el-button>
                <el-button size="mini" type="success" @click="clearileTemplate">清空模板文件</el-button>
                <div slot="tip" class="el-upload__tip" style="text-align: left">只能上传{{fileType}}文件，且不超过{{fileSize}}MB</div>
              </el-upload>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="menu-navbar">
        <el-button size="small" type="" @click="closePage">关闭</el-button>
        <el-button v-if="optType == 'add'" size="small" type="success" @click="createSave('dataForm')">保存</el-button>
        <el-button v-if="optType == 'edit'" size="small" type="success" @click="createUpdate('dataForm')">更新</el-button>
      </div>
    </div>
  </div>
</template>
<script>
  import {
    getTemplateInfo,
    addTemplateInfo,
    editTemplateInfo
  } from '@/api/templateManage/TplTemplateInfo.js'
  import {
    getUuid
  } from '@/api/templateManage/TplCommon.js'
  import { getToken } from '@/utils/auth'

  import {
    statusOptions
  } from '@/utils/allOptions'

  export default {
    name: 'tplTemplateInfoDetailCom',
    data() {
      let codeValid = (rule, value, callback) => {
        if (!value) {
          return callback()
        }
        setTimeout(() => {
          let reg = '[^a-zA-Z0-9_-]+'
          let regus = new RegExp(reg)
          if (!regus.test(value)) {
            callback()
          } else {
            callback(new Error('模板编码只能包含字母、数字、_、-'))
          }
        }, 100)
      }
      let sortValid = (rule, value, callback) => {
        if (!value) {
          return callback()
        }
        setTimeout(() => {
          let reg = '[^0-9]+'
          let regus = new RegExp(reg)
          if (!regus.test(value)) {
            callback()
          } else {
            callback(new Error('排序号只能包含数字'))
          }
        }, 100)
      }
      return {
        fileUploadUrl: process.env.BASE_API + '/file' + '/SysFileInfo/uploadFile',
        fileHeaders: {
          Authorization: 'bearer ' + getToken()
          // 'Content-Type': 'multipart/form-data'
        },
        fileList: [],
        fileLimit: 1,
        fileType: ['txt', 'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'],
        fileSize: 200, // 允许上传文件大小 单位 MB
        fileRecord: {
          busiType: 'templateManage',
          busiSubType: 'templateInfo',
          busiPrimaryKey: ''
        },
        record: {
          id: '',
          code: '',
          title: '',
          keyword: '',
          description: '',
          storageMode: '',
          sort: '',
          status: '',
          remark: '',
          fileId: '',
          fileName: '',
          fileSize: null,
          fileRelativePath: ''
        },
        recordfileSizeName: '',
        statusOptions: statusOptions,
        storageModeOptions: [
          {
            key: '1',
            display_name: '本地文件系统'
          },
          {
            key: '2',
            display_name: '第三方文件系统'
          }
        ],
        recordRules: {
          title: [
            { message: '模板标题不能为空', required: true, trigger: 'blur' },
            { min: 1, max: 128, message: '最大长度为 128 个字符', trigger: 'blur' }
          ],
          code: [
            { message: '模板编码不能为空', required: true, trigger: 'blur' },
            { min: 1, max: 128, message: '最大长度为 128 个字符', trigger: 'blur' },
            { validator: codeValid, trigger: 'blur' }
          ],
          keyword: [
            { min: 1, max: 512, message: '最大长度为 512 个字符', trigger: 'blur' }
          ],
          description: [
            { min: 1, max: 1024, message: '最大长度为 1024 个字符', trigger: 'blur' }
          ],
          storageMode: [
            { message: '存储方式不能为空', required: true, trigger: 'change' }
          ],
          sort: [
            { message: '排序号不能为空', required: true, trigger: 'blur' },
            { min: 1, max: 8, message: '最大长度为 8 个字符', trigger: 'blur' },
            { validator: sortValid, trigger: 'blur' }
          ],
          status: [
            { message: '模板状态不能为空', required: true, trigger: 'change' }
          ],
          remark: [
            { min: 1, max: 1024, message: '最大长度为 200 个字符', trigger: 'blur' }
          ]
        },
        optType: '', // 操作类型
        recordPkId: '' // 修改主键ID
      }
    },
    props: ['componentCustomProps'],
    created() {
      this.initPage()
    },
    watch: {
      //
    },
    methods: {
      initPage() {
        this.optType = this.componentCustomProps.editType
        this.recordPkId = this.componentCustomProps.id

        for (let key in this.record) {
          this.record[key] = ''
        }
        this.fetchData()
      },
      fetchData() {
        if (this.$refs['dataForm']) {
          this.$refs['dataForm'].clearValidate()
        }
        if (this.optType === 'add') {
          this.record.storageMode = '1'
          this.record.status = '0'
          this.record.sort = '01'

          this.loading = true
          getUuid().then(res => {
            this.loading = false
            if (res.data.success) {
              this.record.id = res.data.data
              this.fileRecord.busiPrimaryKey = this.record.id
            } else {
              this.$message({
                type: 'error',
                message: '模板信息ID失败！'
              })
            }
            console.log('id=' + this.record.id)
          }).catch((err) => {
            console.log(err)
          })
        } else if (this.optType === 'edit') {
          this.loading = true
          getTemplateInfo(this.recordPkId).then(res => {
            this.loading = false
            if (res.data.success) {
              this.record = res.data.data
              this.recordfileSizeName = this.fileSizeFormat(this.record.fileSize)
              this.fileRecord.busiPrimaryKey = this.record.id
            } else {
              this.$message({
                type: 'error',
                message: '获取模板信息详细失败！'
              })
            }
          }).catch((err) => {
            console.log(err)
          })
        }
      },
      submitUpload() {
        // if (this.fileList == null || this.fileList.length <= 0) {
        //   this.$message({
        //     type: 'error',
        //     message: '请选择上传的文档!'
        //   })
        //   return false
        // }
        //
        // for (let i = 0; i < this.fileList.length; i++) {
        //   let tempFile = this.fileList[i]
        //   let size = tempFile.size
        //   if (size > this.fileSize * 1024 * 1024) {
        //     this.$message({
        //       type: 'error',
        //       message: '上传文档太大!'
        //     })
        //     return false
        //   }
        //
        //   let tempName = tempFile.name
        //   let type = tempName.substring(tempName.lastIndexOf('.') + 1)
        //   if (type) {
        //     type = type.toLocaleLowerCase()
        //   }
        //   let bool = this.fileType.includes(type)
        //   if (!bool) {
        //     this.$message({
        //       type: 'error',
        //       message: '上传文档类型错误!'
        //     })
        //     return false
        //   }
        // }
        this.$refs.upload.submit()
      },
      handleChange(file, fileList) {
        // console.log(fileList)
        // this.fileList = fileList
      },
      handleRemove(file, fileList) {
        // this.fileList = fileList
      },
      handleExceed(files, fileList) {
        fileList[0].raw = files[0]
        fileList[0].name = files[0].name
        fileList[0].size = files[0].size
        // this.$set(fileList[0], 'raw', files[0])
        // this.$set(fileList[0], 'name', files[0].name)
        this.$refs.upload.clearFiles() // 清除文件
        this.$refs.upload.handleStart(files[0]) // 选择文件后的赋值方法
      },
      handleBeforeUpload(file) {
        let tempFile = file
        let size = tempFile.size
        if (size > this.fileSize * 1024 * 1024) {
          this.$message({
            type: 'error',
            message: '上传文档太大!'
          })
          return false
        }

        let tempName = tempFile.name
        let type = tempName.substring(tempName.lastIndexOf('.') + 1)
        if (type) {
          type = type.toLocaleLowerCase()
        }
        let bool = this.fileType.includes(type)
        if (!bool) {
          this.$message({
            type: 'error',
            message: '上传文档类型错误!'
          })
          return false
        }
      },
      handleSuccess(response) {
        if (response.success) {
          this.$message({
            type: 'success',
            message: '上传成功!'
          })
          this.$refs.upload.clearFiles()

          this.record.fileId = response.data.id
          this.record.fileName = response.data.fileName
          this.record.fileSize = response.data.fileSize
          this.record.fileRelativePath = response.data.fileRelativePath
          this.recordfileSizeName = this.fileSizeFormat(this.record.fileSize)
        } else {
          this.$message({
            type: 'error',
            message: response.message
          })
        }
      },
      handleError(file, fileList) {
        this.fileList = []
        this.$message({
          type: 'error',
          message: '上传失败!'
        })
      },
      clearileTemplate() {
        this.record.fileId = ''
        this.record.fileName = ''
        this.record.fileSize = 0
        this.record.fileRelativePath = ''
        this.recordfileSizeName = ''
      },
      createSave(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.customValid()) {
              this.saveRecord()
            }
          } else {
            this.$message({
              type: 'error',
              message: '添加失败!'
            })
            console.log('error save!!')
            return false
          }
        })
      },
      createUpdate(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.customValid()) {
              this.updateRecord()
            }
          } else {
            this.$message({
              type: 'error',
              message: '更新失败!'
            })
            console.log('error update!!')
            return false
          }
        })
      },
      saveRecord() {
        addTemplateInfo(this.record).then(res => {
          if (res.data.success) {
            this.$message({
              type: 'success',
              message: '保存成功!'
            })
            this.componentCustomProps.editType = 'edit'
            this.componentCustomProps.id = res.data.data.id
            this.initPage()
            this.$emit('refreshList')
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            })
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      updateRecord() {
        editTemplateInfo(this.record, this.record.id).then(res => {
          if (res.data.success) {
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            this.componentCustomProps.editType = 'edit'
            this.componentCustomProps.id = this.record.id
            this.initPage()
            this.$emit('refreshList')
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            })
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      customValid() {
        let bool = true
        if (this.record.storageMode === '1') {
          if (!this.record.fileId || this.record.fileId === '') {
            this.$message({
              type: 'warning',
              message: '请选择并上传模板文件!'
            })
            bool = false
          }
        } else if (this.record.storageMode === '2') {
          //
        }
        return bool
      },
      closePage() {
        this.$emit('closeDialog')
      },
      fileSizeFormat(num) {
        if (num <= 0) {
          return ''
        }
        let unit = ' B'
        if (num > 1024 * 2014) {
          num = num / 1024
          unit = ' KB'
        }
        if (num > 1024 * 2014) {
          num = num / 1024
          unit = ' MB'
        }
        if (num > 1024 * 2014) {
          num = num / 1024
          unit = ' GB'
        }
        if (num > 1024 * 2014) {
          num = num / 1024
          unit = ' TB'
        }
        return Math.round(num) + unit
      }
    }
  }
</script>
<style scoped>
  .menu-navbar{
    padding:0 0 20px;
    text-align: right;
  }
  .container{
    padding: 0 10px;
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;
  }
</style>
